import 'dart:async';
import 'dart:convert';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chip/bean/User.dart';
import 'package:flutter_chip/config/Api.dart';
import 'package:flutter_chip/config/Http.dart';
import 'package:flutter_chip/config/Routers.dart';
import 'package:flutter_chip/utils/toast_utils.dart';
import 'package:mobsms/mobsms.dart';
import 'package:provide/provide.dart';

class CheckPhonePage extends StatefulWidget {
  final String title;
  final String phone;

  const CheckPhonePage({Key key, this.title, this.phone}) : super(key: key);

  @override
  _CheckPhonePageState createState() => _CheckPhonePageState();
}

class _CheckPhonePageState extends State<CheckPhonePage> {
  final _formKey = GlobalKey<FormState>();
  var _phoneController = TextEditingController();
  var _verifyController = TextEditingController();
  String _phone;

  //手机号不为空则在本页完成校验和绑定，通过step控制
  int step = -1;

  //倒计时按钮
  Timer _countTimer;
  String _btnStr = '获取验证码';
  int _count = 60;

  //手机号是否可编辑
  bool _canEdit = true;

  //标题
  String _title;

  //user
  User user;

  @override
  void initState() {
    super.initState();
    if (null != widget.phone) {
      _phoneController.value = TextEditingValue(text: widget.phone);
      _canEdit = false;
    }
    if (widget.title == "wjmm") {
      _title = "忘记密码";
    } else if (widget.title == "xgmm") {
      _title = "修改密码";
    } else if (widget.title == "bdsj") {
      _title = "绑定手机号";
      if (null != widget.phone) {
        step = 1;
      }
    }
    if (null != widget.phone) {
      _title = "校验手机号";
    }
  }

  @override
  Widget build(BuildContext context) {
    user = Provide.value<User>(context);
    return Scaffold(
      appBar: AppBar(
          elevation: 1.0,
          backgroundColor: Theme.of(context).canvasColor,
          titleSpacing: 0.0,
          title: Text(
            _title,
            style: TextStyle(fontSize: 18),
          ),
          centerTitle: true),
      body: Form(
        key: _formKey,
        child: ListView(
          padding: EdgeInsets.symmetric(horizontal: 22.0),
          children: <Widget>[
            SizedBox(height: 40),
            buildPhoneTextField(),
            SizedBox(height: 20),
            buildVerifyTextField(),
            SizedBox(height: 30),
            buildRegisterButton(context)
          ],
        ),
      ),
    );
  }

  Widget buildPhoneTextField() {
    return TextFormField(
      // ignore: missing_return
      validator: (String value) {
        var emailReg = RegExp(
            r'^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$');
        if (!emailReg.hasMatch(value)) {
          return '请输入正确的手机号';
        }
      },
      enabled: _canEdit,
      onSaved: (String value) => _phone = value,
      keyboardType: TextInputType.phone,
      controller: _phoneController,
      decoration: InputDecoration(
        labelText: '手机号',
        hintText: '请输入手机号',
        contentPadding: EdgeInsets.all(10),
        prefixIcon: Icon(Icons.smartphone),
        border: OutlineInputBorder(
          borderSide: BorderSide(
            color: Theme.of(context).accentColor,
          ),
          borderRadius: BorderRadius.all(
            Radius.circular(24),
          ),
        ),
      ),
    );
  }

  Widget buildVerifyTextField() {
    return TextField(
      keyboardType: TextInputType.number,
      controller: _verifyController,
      decoration: InputDecoration(
        labelText: '验证码',
        hintText: '请输入验证码',
        contentPadding: EdgeInsets.all(10),
        prefixIcon: Icon(Icons.beenhere),
        suffixIcon: FlatButton(
            onPressed: () {
              FocusScope.of(context).requestFocus(FocusNode());
              sendVerify();
            },
            child: Text(_btnStr,
                style: TextStyle(
                    color: _count == 60
                        ? Theme.of(context).accentColor
                        : Colors.black38))),
        border: OutlineInputBorder(
          borderSide: BorderSide(color: Theme.of(context).accentColor),
          borderRadius: BorderRadius.all(
            Radius.circular(24),
          ),
        ),
      ),
    );
  }

  ///发送验证码
  void sendVerify() {
    if (_countTimer != null) {
      return;
    }
    _phone = _phoneController.text;
    print('输入的手机号是：$_phone');
    if (_phone.isEmpty) {
      Toast.show("请填写正确的手机号");
      return;
    }
    CancelFunc cancelFunc = Toast.loading("发送中...");
    Smssdk.getTextCode(_phoneController.text, "86", "", (dynamic ret, Map err) {
      cancelFunc();
      if (null != err) {
        print("$err");
        Toast.show(err["msg"]);
      } else {
        Toast.show("验证码已发送");
        countDownTimer();
      }
    });
  }

  ///倒计时按钮
  void countDownTimer() {
    if (_countTimer != null) {
      return;
    }
    _btnStr = '${_count--}s重新获取';
    _countTimer = Timer.periodic(Duration(seconds: 1), (timer) {
      print("$_count");
      setState(() {
        if (_count > 0) {
          _btnStr = '${_count--}s后重新获取';
        } else {
          _btnStr = '获取验证码';
          _count = 60;
          _countTimer.cancel();
          _countTimer = null;
        }
      });
    });
  }

  void checkVerify() {
    String verifyCode = _verifyController.text;
    if (verifyCode.isEmpty) {
      Toast.show("验证码不能为空");
      return;
    }
    print("校验验证码：$_phone $verifyCode");
    CancelFunc cancelFunc = Toast.loading("校验中...");
    Smssdk.commitCode(_phone, "86", _verifyController.text,
        (dynamic ret, Map err) {
      cancelFunc();
      if (null != err) {
        Toast.show(err["msg"]);
      } else {
        Toast.show("校验成功");
        if (widget.title == "bdsj") {
          if (step == 1) {
            setState(() {
              _title = "修改手机号";
              _canEdit = true;
              _phoneController.value = TextEditingValue(text: "");
              step = 2;
              _btnStr = '获取验证码';
              _count = 60;
              _countTimer.cancel();
              _countTimer = null;
            });
          } else {
            _submit();
          }
        } else {
          Toast.show("校验成功");
          Routers.router.navigateTo(context,
              '${Routers.PAGE_SETPWD}?phone=$_phone&type=${widget.title}',
              replace: true);
        }
      }
    });
  }

  ///下一步按钮
  Align buildRegisterButton(BuildContext context) {
    return Align(
      child: SizedBox(
        height: 45.0,
        width: MediaQuery.of(context).size.width,
        child: RaisedButton(
          child: Text(
            '下一步',
            style: TextStyle(color: Colors.white, fontSize: 18),
          ),
          color: Theme.of(context).accentColor,
          onPressed: () {
            if (_formKey.currentState.validate()) {
              _formKey.currentState.save();
              FocusScope.of(context).requestFocus(FocusNode());
              checkVerify();
            }
          },
          shape: StadiumBorder(
            side: BorderSide(color: Theme.of(context).accentColor),
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    if (null != _countTimer) {
      _countTimer.cancel();
      _countTimer = null;
    }
  }

  ///保存修改
  Future _submit() async {
    Map<String, String> params = Map();
    params["phone"] = _phoneController.text;
    CancelFunc cancelFunc = Toast.loading("绑定中...");
    Http.post(Api.URL_USER_UPDATE, params: params, successCallBack: (data) {
      cancelFunc();
      Toast.show("绑定成功");
      if (null != user) {
        user.update(User.fromJson(json.decode(data)));
      }
      Routers.router.pop(context);
    }, errorCallBack: (error) {
      cancelFunc();
      Toast.show(error);
    });
  }
}
